import React, { useState, useEffect } from 'react';
import moment from 'moment';
// @ts-ignore
import { TjStation, TjSelect } from '@/pages/ETrade/components';
import { useDebounceFn } from 'ahooks';
import _ from 'lodash';
import { DatePicker, Form, Space, Button, Input, Select, Popconfirm } from 'antd';
import { PlusOutlined, UploadOutlined } from '#/utils/antdIcons.js';
import { ExplainSelect } from '../index';
import {
  tradeDirectionOptions,
  contractSourceOptions,
  positionsCalculateOptions,
  contractSourceHintText,
  positionsCalculateHintText,
} from '../../dictionary';
import type { IFromValue, ISearchFormData } from '../../type';
import styles from './index.less';
import { useTRState } from '#/utils/trHooks';
import { getContractTypeCodes } from '@/pages/ETrade/ContractManagement/service';
import { HttpCode } from '#/utils/contacts.js';
import ExportBtn from '../ExportBtn';

interface IProps {
  /**
   * 表单值
   */
  values?: IFromValue;
  /**
   * 是否禁用
   */
  disabled?: boolean;
  /**
   * 表单初始值
   */
  initialValues?: IFromValue;
  /**
   * 表单选项值
   */
  searchFormData?: ISearchFormData;
  /**
   * 新建合约
   */
  addContract?: () => void;
  /**
   * 导出数据
   */
  handleExportFiles?: (formValue?: any) => void;
  /**
   * 搜索数据
   */
  onChange?: (values: IFromValue) => void;
  /**
   * 场站的数据
   */
  power?: any[];
  /**
   * 已选省份场站
   */
  stationOptions?: any[];
}

const Header = (props: IProps) => {
  const [form] = Form.useForm();
  const {
    getStationData,
    power = [],
    stationOptions = [],
    values = {},
    initialValues = {},
    contractTypeList = [],
    disabled = false,
    addContract,
    handleExportFiles,
    onChange,
  } = props;
  const [visible, setVisible] = useState(false); // 控制大数据查询前提示
  const [isXinJiang, setIsXinJiang] = useState(false);
  const [state, setState] = useTRState({
    provinceIds: [],
    contractTypeList: [],
    checkedList: [],
    indeterminate: true,
    checkAll: false,
  });

  useEffect(() => {
    const checkedList: any = [];
    contractTypeList?.forEach((c: any) => {
      checkedList.push(c?.value);
    });
    setState({
      checkedList,
      contractTypeList,
    });
  }, [contractTypeList]);

  useEffect(() => {
    const { beginDate, endDate, ...rest } = values;
    const _values = {
      date: beginDate && endDate ? [moment(beginDate), moment(endDate)] : [],
      ...rest,
    };
    form && form.setFieldsValue(_values);
    setState({
      checkedList: _values?.contractTypeCodes,
    });
  }, [values]);

  // 重置
  const onReset = () => {
    const { beginDate, endDate, ...rest } = initialValues;
    const _values = {
      date: beginDate && endDate ? [moment(beginDate), moment(endDate)] : [],
      ...rest,
    };
    form && form.setFieldsValue(_values);
    onChange && onChange(initialValues);
  };

  const confirm = useDebounceFn(
    () => {
      setVisible(false);
      form && form.submit();
    },
    { wait: 500 },
  );

  const handleVisibleChange = (newVisible?: boolean) => {
    const { date, stationIdList } = form.getFieldsValue();
    if (date && stationIdList.length > 0) {
      const days = date[1].diff(date[0], 'days') + 1;
      if (days * stationIdList.length > 900) {
        setVisible(!!newVisible);
      } else {
        confirm.run();
      }
    } else if (!date || !stationIdList.length) {
      setVisible(false);
    } else {
      confirm.run();
    }
  };

  // 搜索
  const onFinish = (data: any) => {
    const { date, ...rest } = data;
    const _fromValue = {
      beginDate: isXinJiang
        ? moment(date[0]).startOf('months').format('YYYY-MM-DD')
        : moment(date[0]).format('YYYY-MM-DD'),
      endDate: isXinJiang
        ? moment(date[1]).endOf('months').format('YYYY-MM-DD')
        : moment(date[1]).format('YYYY-MM-DD'),
      ...rest,
    };
    onChange && onChange(_fromValue);
  };

  const onChangeRegion = async (v: any, opt: any) => {
    const regionId = opt.value2;
    // 如果选中的省份为新疆
    setIsXinJiang(regionId === '65');
    const { stationList } = getStationData(power, v);
    form.setFieldsValue({
      regionId,
      stationIdList: stationList,
    });
    //请求合约类型
    const contractTypeRes = await getContractTypeCodes({
      provinceIds: [regionId],
    });
    if (contractTypeRes?.statusCode === HttpCode.SUCCESS) {
      const contractTypeCodes: string[] = [],
        _contractTypeList: any[] = [];
      contractTypeRes?.data?.forEach((d: any) => {
        if (!contractTypeCodes.includes(d?.contractTypeCode)) {
          contractTypeCodes.push(d?.contractTypeCode);
        }
        _contractTypeList.push({
          label: d?.contractTypeName,
          value: d?.contractTypeCode,
        });
      });
      setState({
        contractTypeList: _contractTypeList,
        checkedList: contractTypeCodes,
      });
      form.setFieldsValue({ contractTypeCodes });
    }
  };

  // 新增合约
  const _addContract = () => {
    addContract && addContract();
  };

  // 导出文件
  const _handleExportFiles = () => {
    if (!disabled) {
      handleExportFiles && handleExportFiles();
    }
  };

  return (
    <div className={styles.container}>
      <Form
        form={form}
        name="filter"
        initialValues={initialValues}
        requiredMark={false}
        colon={false}
        autoComplete="off"
        onFinish={onFinish}
      >
        <Form.Item name="date" rules={[{ required: true, message: '请选择时间' }]}>
          {isXinJiang ? (
            <DatePicker.RangePicker
              format="YYYYMM"
              picker="month"
              placeholder={['请选择', '请选择']}
              className={styles.datePicker}
              separator="-"
            />
          ) : (
            <DatePicker.RangePicker
              format="YYYYMMDD"
              placeholder={['请选择', '请选择']}
              className={styles.datePicker}
              separator="-"
            />
          )}
        </Form.Item>
        <Form.Item name={'provinceId'}>
          <Select style={{ width: 200 }} options={power} onChange={onChangeRegion} />
        </Form.Item>
        <Form.Item name={'regionId'} noStyle />
        <Form.Item name="stationIdList" rules={[{ required: true, message: '请选择交易单元' }]}>
          <TjStation
            style={{ width: 160, fontWeight: 400, fontSize: 12 }}
            options={stationOptions}
          />
        </Form.Item>
        <Form.Item name="contractTypeCodes" rules={[{ required: true, message: '请选择合约类型' }]}>
          <TjSelect
            style={{ width: 120 }}
            options={state.contractTypeList}
            showSearch
            mode="multiple"
            label="合约类型"
          />
        </Form.Item>
        <Form.Item name="tradeRoleList" rules={[{ required: true, message: '请选择交易方向' }]}>
          <Select
            className={styles.select}
            placeholder="请选择"
            showArrow={true}
            options={tradeDirectionOptions as any}
          />
        </Form.Item>
        <Form.Item
          name="contractSourceList"
          rules={[{ required: true, message: '请选择合约来源' }]}
        >
          <ExplainSelect
            placeholder="请选择"
            showArrow={true}
            bordered={false}
            style={{ width: 93 }}
            options={contractSourceOptions}
            hintText={contractSourceHintText}
          />
        </Form.Item>
        <Form.Item name="keyWords">
          <Input placeholder="关键字" style={{ width: 120 }} />
        </Form.Item>
        <Form.Item
          name="storageCapacityCalcList"
          rules={[{ required: true, message: '请选择参与仓位计算' }]}
        >
          <ExplainSelect
            placeholder="请选择"
            showArrow={true}
            bordered={false}
            style={{ width: 93 }}
            hintText={positionsCalculateHintText}
            options={positionsCalculateOptions as any}
          />
        </Form.Item>
        {/* {isXinJiang && (
          <Form.Item name="userTypeList" rules={[{ required: true, message: '请选择用户类型' }]}>
            <TjSelect
              value={state.columnsType}
              style={{ width: 120 }}
              options={USER_TYPE_DIC}
              showSearch
              mode="multiple"
              label="数据类型"
            />
          </Form.Item>
        )} */}
        <Space size={'middle'}>
          <Popconfirm
            title="您选择的数据量较大，可能延长加载时间或引起页面崩溃，是否确认查询？"
            visible={visible}
            onVisibleChange={handleVisibleChange}
            onConfirm={() => confirm.run()}
            onCancel={() => setVisible(false)}
            okText="确认"
            cancelText="取消"
          >
            <Button type="primary" htmlType="submit" className={styles.searchBtn}>
              查询
            </Button>
          </Popconfirm>
          <Button onClick={onReset} className={styles.searchBtn}>
            重置
          </Button>
        </Space>
      </Form>
      <div className={styles.explainOption}>
        <div className={styles.button} onClick={_addContract}>
          <PlusOutlined className={styles.buttonLogo} />
          新建合约
        </div>
        {values?.provinceId === '65' ? (
          <ExportBtn
            form={form}
            stationOptions={_.flattenDeep(
              stationOptions?.map((a: any) =>
                a?.children?.map((b: any) => ({ label: b.label, value: b.value })),
              ),
            )}
          />
        ) : (
          ''
        )}

        <div
          className={`${disabled && styles.disabledButton} ${styles.button}`}
          onClick={_handleExportFiles}
        >
          <UploadOutlined
            className={`${disabled && styles.disabledButtonLogo} ${styles.buttonLogo}`}
          />
          导出
        </div>
      </div>
    </div>
  );
};

export default Header;
